import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

export interface User {
  id: number;
  username: string;
  password: string;
  realName: string;
  role: string;
}

export interface RegisterUserData {
  username: string;
  password: string;
  realName: string;
  role: string;
}

export interface UpdateUserData extends RegisterUserData {
  id: number;
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    users: [] as User[],
  }),

  actions: {
    setUser(userData: User | null) {
      this.user = userData;
    },

    async login(username: string, password: string) {
      try {
        const response = await axios.post('/api/user/login', { username, password });
        if (response.data.code === 200) {
          this.setUser(response.data.data);
          return response.data.data;
        } else {
          throw new Error(response.data.message || '登录失败');
        }
      } catch (error: any) {
        throw new Error(error.response?.data?.message || '登录失败');
      }
    },

    async register(userData: RegisterUserData) {
      try {
        const response = await axios.post('/api/user/register', userData);
        if (response.data.code === 200) {
          this.setUser(response.data.data);
          return response.data.data;
        } else {
          throw new Error(response.data.message || '注册失败');
        }
      } catch (error: any) {
        throw new Error(error.response?.data?.message || '注册失败');
      }
    },

    async updateUser(userData: UpdateUserData) {
      try {
        const response = await axios.put('/api/user', userData);
        if (response.data.code === 200) {
          this.setUser(response.data.data);
          return response.data.data;
        } else {
          throw new Error(response.data.message || '更新用户信息失败');
        }
      } catch (error: any) {
        throw new Error(error.response?.data?.message || '更新用户信息失败');
      }
    },

    async deleteUser(id: number) {
      try {
        const response = await axios.delete(`/api/user?id=${id}`);
        if (response.data.code === 200) {
          // Remove the user from the users array if it exists
          this.users = this.users.filter(user => user.id !== id);
          if (this.user?.id === id) {
            this.setUser(null);
          }
          return true;
        } else {
          throw new Error(response.data.message || '删除用户失败');
        }
      } catch (error: any) {
        throw new Error(error.response?.data?.message || '删除用户失败');
      }
    },

    async fetchUserInfo(userId: number) {
      try {
        const response = await axios.get(`/api/user/${userId}`);
        if (response.data.code === 200) {
          this.setUser(response.data.data);
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取用户信息失败');
        }
      } catch (error: any) {
        throw new Error(error.response?.data?.message || '获取用户信息失败');
      }
    },

    async fetchUsers() {
      try {
        const response = await axios.get('/api/user/all');
        if (response.data.code === 200) {
          this.users = response.data.data;
          return this.users;
        } else {
          throw new Error(response.data.message || '获取用户列表失败');
        }
      } catch (error: any) {
        throw new Error(error.response?.data?.message || '获取用户列表失败');
      }
    },

    logout() {
      this.user = null;
    },
  },
});